
const fs = require("fs");
const path = require("path")


// 删除本地文件
function deleteLocalFile(filePath) {
    return new Promise((resolve,rej)=>{
      fs.unlink(filePath, (err) => {
        if (err) {
          console.error(`Failed to delete file: ${filePath}`);
          rej(err)
        } else {
          console.log(`File deleted: ${filePath}`);
          resolve(filePath)
        }
      });
    } )
  }
//
const deleteFolder = function(folderPath) {
  if (fs.existsSync(folderPath)) {
    fs.readdirSync(folderPath).forEach((file, index) => {
      const curPath = folderPath + "/" + file;
      if (fs.lstatSync(curPath).isDirectory()) {
        // 递归删除子文件夹
        deleteFolder(curPath);
      } else {
        // 删除文件
        fs.unlinkSync(curPath);
      }
    });
    // 删除空文件夹
    fs.rmdirSync(folderPath);
    console.log(`成功删除文件夹: ${folderPath}`);
  } else {
    console.log(`文件夹不存在: ${folderPath}`);
  }
};  

  //
  function deleteFilesByFilename(folderPath, fileName) {
    console.log("删除开始")
    fs.readdir(folderPath, (err, files) => {
      if (err) {
        console.error('读取文件夹失败：', err);
        return;
      }
  
      try {
        files.forEach(file => {
          const filePath = path.join(folderPath, file);
          const stats = fs.statSync(filePath);
    
          if (stats.isFile() && file === fileName) {
            fs.unlink(filePath, err => {
              if (err) {
                console.error('删除文件失败：', err);
              } else {
                console.log('成功删除文件：', filePath);
              }
            });
          } else if (stats.isDirectory()) {
            deleteFilesByFilename(filePath, fileName); // 递归调用删除子文件夹中的文件
            
          }
        });
      } catch (error) {
        
      }
    });
  }
  function clearFolder(folderPath) {
    // 获取文件夹中的所有文件和子文件夹
    const files = fs.readdirSync(folderPath);

    files.forEach((file) => {
        const filePath = path.join(folderPath, file);

        // 判断文件类型
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            // 如果是文件，则直接删除
            fs.unlinkSync(filePath);
        } else {
            // 如果是文件夹，则递归调用清空文件夹方法
            clearFolder(filePath);
            // 删除空文件夹
            fs.rmdirSync(filePath);
        }
    });
}

  module.exports = {
    deleteLocalFile,
    deleteFilesByFilename,
    deleteFolder,
    clearFolder
}